import router from "./router";
import { userStore } from "./store/user";
import { menuStore } from "./store/menu";

//定义白名单
const whiteList = ['/login']
router.beforeEach(async (to, from, next) => {
    const usStore = userStore();
    const msStore = menuStore();
    //获取token
    const token = usStore.getToken
    //判断token是否存在
    if (token) {
        //判断是否登录或首页：是 放行  不是：从服务器获取菜单数据
        if (to.path === '/login' || to.path === '/') {
            next({ path: '/' })
        } else {
            //判断权限数据是否存在
            const hasRoles = usStore.getCodeList.length > 0
            if (hasRoles) { //存在 放行
                next()
            }
            else {
                try {
                    //获取用户信息
                    await usStore.getInfo()
                    //获取菜单数据
                    await msStore.getMenuList(router, usStore.getUserId)
                    //等待路由完全挂载
                    next({ ...to, replace: true })
                } catch (error) {
                    sessionStorage.clear()//清空数据
                    next({path:'/login'})
                }
            }

        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) { //说明在白名单，放行
            next()
        } else { //不在白名单
            next({ path: '/login' })
        }
    }
})